package cn.com.fuhuitong.main.home.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import cn.com.fuhuitong.app.BaseApplication
import cn.com.fuhuitong.base.BaseViewModel
import cn.com.fuhuitong.http.HttpResponse
import cn.com.fuhuitong.http.ViewModelSubscribeListener
import cn.com.fuhuitong.main.home.entity.CharityListResponse
import cn.com.fuhuitong.main.home.entity.HomeGoodsResponse
import cn.com.fuhuitong.main.home.entity.HomeResponse
import cn.com.fuhuitong.main.home.mode.HomeManager
import io.reactivex.disposables.Disposable

class HomeViewModel(application: Application) : BaseViewModel(application) {
    private val homeManager: HomeManager = HomeManager()

    val homeDataLiveData = MutableLiveData<HttpResponse<HomeResponse>>()
    val homeGoodsDataLiveData = MutableLiveData<HttpResponse<HomeGoodsResponse>>()
    val charityListDataLiveData = MutableLiveData<HttpResponse<CharityListResponse>>()


    /**
     * 获取首页默认数据
     */
    fun homeIndex() {
        val listener = object : ViewModelSubscribeListener<HomeResponse>(homeDataLiveData) {}
        val homeIndexDisposable: Disposable = homeManager.homeIndex(listener)
        dispose.add(homeIndexDisposable)
    }

    private var page: Int = 1
    private var limit: Int = 20

    /**
     * 获取首页好物推荐数据
     */
    fun homeGoods(restart: Boolean = false) {
        val listener =
            object : ViewModelSubscribeListener<HomeGoodsResponse>(homeGoodsDataLiveData) {
                override fun onSuccess(resp: HomeGoodsResponse) {
                    super.onSuccess(resp)
                    resp.loadMore = page > 1
                    super.onSuccess(resp)
                    page += 1
                }
            }
        if (restart) page = 1
        val homeIndexDisposable: Disposable =
            homeManager.homeGoods(page.toString(), limit.toString(), listener)
        dispose.add(homeIndexDisposable)
    }

    /**
     * 获取首页好物推荐数据
     */
    fun charityIndex(type: String) {
        val listener =
            object : ViewModelSubscribeListener<CharityListResponse>(charityListDataLiveData) {}
        val charityIndexDisposable: Disposable = homeManager.charityIndex(
            BaseApplication.userToken(),
            page.toString(),
            limit.toString(),
            type, listener
        )
        dispose.add(charityIndexDisposable)
    }
}